/******************************************************************
系统名称:E比价
类  名  称: CreateLockPatternActivity.java
软件版权: 恒生电子股份有限公司
系统版本: 1.0
开发人员: maqf
开发时间: 2015-04-01
功能说明: 创建手势密码
审核人员: 
相关文档: 
修改记录: 需求编号         修改日期         修改人员                     修改说明
 
******************************************************************/
package com.hundsun.fcp.activity;


import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.hundsun.fcp.R;
import com.hundsun.fcp.base.BaseActivity;
import com.hundsun.fcp.widget.lockpattern.LockPatternUtils;
import com.hundsun.fcp.widget.lockpattern.LockPatternView;
import com.hundsun.fcp.widget.lockpattern.LockPatternView.Cell;
import com.hundsun.fcp.widget.lockpattern.LockPatternView.DisplayMode;

public class LockPatternCreateActivity extends BaseActivity{
	private static final int ID_EMPTY_MESSAGE = -1;
	private static final String KEY_UI_STAGE = "uiStage";
	private static final String KEY_PATTERN_CHOICE = "chosenPattern";
	private LockPatternView mLockPatternView;
	protected TextView mHeaderText;
	private TextView mResetTextView ;
	protected List<LockPatternView.Cell> mChosenPattern = null;
	private Toast mToast;
	private Stage mUiStage = Stage.Introduction;
	
	private LockPatternUtils mLockPatternUtils;
	
	private final List<LockPatternView.Cell> mAnimatePattern = new ArrayList<LockPatternView.Cell>();
	
	protected View[][] mPreViews = (View[][])Array.newInstance(View.class, new int[] { 3, 3 });

	/**
	 * The states of the left footer button.
	 */
	enum LeftButtonMode {
		Cancel(android.R.string.cancel, true), CancelDisabled(
				android.R.string.cancel, false), Retry(
				R.string.lockpattern_retry_button_text, true), RetryDisabled(
				R.string.lockpattern_retry_button_text, false), Gone(
				ID_EMPTY_MESSAGE, false);

		/**
		 * @param text
		 *            The displayed text for this mode.
		 * @param enabled
		 *            Whether the button should be enabled.
		 */
		LeftButtonMode(int text, boolean enabled) {
			this.text = text;
			this.enabled = enabled;
		}

		final int text;
		final boolean enabled;
	}

	/**
	 * The states of the right button.
	 */
	enum RightButtonMode {
		Continue(R.string.lockpattern_continue_button_text, true), ContinueDisabled(
				R.string.lockpattern_continue_button_text, false), Confirm(
				R.string.lockpattern_confirm_button_text, true), ConfirmDisabled(
				R.string.lockpattern_confirm_button_text, false), Ok(
				android.R.string.ok, true);

		/**
		 * @param text
		 *            The displayed text for this mode.
		 * @param enabled
		 *            Whether the button should be enabled.
		 */
		RightButtonMode(int text, boolean enabled) {
			this.text = text;
			this.enabled = enabled;
		}

		final int text;
		final boolean enabled;
	}

	/**
	 * Keep track internally of where the user is in choosing a pattern.
	 */
	protected enum Stage {

		Introduction(R.string.lockpattern_recording_intro_header,
				LeftButtonMode.Cancel, RightButtonMode.ContinueDisabled,
				ID_EMPTY_MESSAGE, true), HelpScreen(
				R.string.lockpattern_settings_help_how_to_record,
				LeftButtonMode.Gone, RightButtonMode.Ok, ID_EMPTY_MESSAGE,
				false), ChoiceTooShort(
				R.string.lockpattern_recording_incorrect_too_short,
				LeftButtonMode.Retry, RightButtonMode.ContinueDisabled,
				ID_EMPTY_MESSAGE, true), FirstChoiceValid(
				R.string.lockpattern_pattern_entered_header,
				LeftButtonMode.Retry, RightButtonMode.Continue,
				ID_EMPTY_MESSAGE, false), NeedToConfirm(
				R.string.lockpattern_need_to_confirm, LeftButtonMode.Cancel,
				RightButtonMode.ConfirmDisabled, ID_EMPTY_MESSAGE, true), ConfirmWrong(
				R.string.lockpattern_need_to_unlock_wrong,
				LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled,
				ID_EMPTY_MESSAGE, true), ChoiceConfirmed(
				R.string.lockpattern_pattern_confirmed_header,
				LeftButtonMode.Cancel, RightButtonMode.Confirm,
				ID_EMPTY_MESSAGE, false);

		/**
		 * @param headerMessage
		 *            The message displayed at the top.
		 * @param leftMode
		 *            The mode of the left button.
		 * @param rightMode
		 *            The mode of the right button.
		 * @param footerMessage
		 *            The footer message.
		 * @param patternEnabled
		 *            Whether the pattern widget is enabled.
		 */
		Stage(int headerMessage, LeftButtonMode leftMode,
				RightButtonMode rightMode, int footerMessage,
				boolean patternEnabled) {
			this.headerMessage = headerMessage;
			this.leftMode = leftMode;
			this.rightMode = rightMode;
			this.footerMessage = footerMessage;
			this.patternEnabled = patternEnabled;
		}

		final int headerMessage;
		final LeftButtonMode leftMode;
		final RightButtonMode rightMode;
		final int footerMessage;
		final boolean patternEnabled;
	}

	private void showToast(CharSequence message) {
		if (null == mToast) {
			mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(message);
		}

		mToast.show();
	}

 
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_UI_STAGE, mUiStage.ordinal());
		if (mChosenPattern != null) {
			outState.putString(KEY_PATTERN_CHOICE,
					LockPatternUtils.patternToString(mChosenPattern));
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (mUiStage == Stage.HelpScreen) {
				updateStage(Stage.Introduction);
				return true;
			}
		}
		if (keyCode == KeyEvent.KEYCODE_MENU && mUiStage == Stage.Introduction) {
			updateStage(Stage.HelpScreen);
			return true;
		}
		return false;
	}

	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};

	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<LockPatternView.Cell> pattern) {
			if (pattern == null)
				return;
			// Log.i("way", "result = " + pattern.toString());
			if (mUiStage == Stage.NeedToConfirm
					|| mUiStage == Stage.ConfirmWrong) {
				if (mChosenPattern == null)
					throw new IllegalStateException(
							"null chosen pattern in stage 'need to confirm");
				if (mChosenPattern.equals(pattern)) {
					//updateStage(Stage.ChoiceConfirmed);
					saveChosenPatternAndFinish() ;
				} else {
					updateStage(Stage.ConfirmWrong);
				}
			} else if (mUiStage == Stage.Introduction
					|| mUiStage == Stage.ChoiceTooShort) {
				if (pattern.size() < LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
					updateStage(Stage.ChoiceTooShort);
				} else {
					mChosenPattern = new ArrayList<LockPatternView.Cell>(
							pattern);
					updateStage(Stage.NeedToConfirm);
				}
			} else {
				throw new IllegalStateException("Unexpected stage " + mUiStage
						+ " when " + "entering the pattern.");
			}
		}

		private void patternInProgress() {
			mHeaderText.setText(R.string.lockpattern_recording_inprogress); 
		}

		@Override
		public void onPatternCellAdded(List<Cell> pattern) {
			
		}
	};

	private void updateStage(Stage stage) {
		mUiStage = stage;
		if (stage == Stage.ChoiceTooShort) {
			mHeaderText.setText(getResources().getString(stage.headerMessage,LockPatternUtils.MIN_LOCK_PATTERN_SIZE));
		} else {
			mHeaderText.setText(stage.headerMessage);
		}

		 
		// same for whether the patten is enabled
		if (stage.patternEnabled) {
			mLockPatternView.enableInput();
		} else {
			mLockPatternView.disableInput();
		}

		mLockPatternView.setDisplayMode(DisplayMode.Correct);

		switch (mUiStage) {
		case Introduction:
			mLockPatternView.clearPattern();
			break;
		case HelpScreen:
			mLockPatternView.setPattern(DisplayMode.Animate, mAnimatePattern);
			break;
		case ChoiceTooShort:
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case FirstChoiceValid:
			break;
		case NeedToConfirm:
			updatePreviewViews() ;
			mResetTextView.setVisibility(View.VISIBLE);
			mLockPatternView.clearPattern();
			break;
		case ConfirmWrong:
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case ChoiceConfirmed:
			break;
		}

	}

	// clear the wrong pattern unless they have started a new one
	// already
	private void postClearPatternRunnable() {
		mLockPatternView.removeCallbacks(mClearPatternRunnable);
		mLockPatternView.postDelayed(mClearPatternRunnable, 100);
	}

 

	private void saveChosenPatternAndFinish() {
		mLockPatternUtils.saveLockPattern(mChosenPattern);
		unlockPattern();
		showToast("密码设置成功");
		setResult(RESULT_OK) ;
		finish();
	}

 

	@Override
	protected int getContentLayout() {
		return R.layout.activity_create_pattern;
	}
	
	@Override
	public void initView() {
		super.initView();
		mLockPatternUtils = new LockPatternUtils(this) ;
		lockPattern() ;
		
		mHeaderText = (TextView) findViewById(R.id.tv_head_tip) ;
		mLockPatternView = (LockPatternView) findViewById(R.id.lockpattern) ;
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		mLockPatternView.setTactileFeedbackEnabled(true);
		mResetTextView = (TextView) findViewById(R.id.tv_reset) ;
		mResetTextView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				clickResetPattern() ;
			}
		}) ;
		initPreViews() ;
	}
	
	@Override
	protected void initHeader() {
		super.initHeader();
		
		mHeaderMenu.setTitle("设置手势密码") ;
	}
	
	  protected void initPreViews()
	  { 
	    this.mPreViews[0][0] = findViewById(R.id.gesturepwd_setting_preview_0);
	    this.mPreViews[0][1] = findViewById(R.id.gesturepwd_setting_preview_1);
	    this.mPreViews[0][2] = findViewById(R.id.gesturepwd_setting_preview_2);
	    this.mPreViews[1][0] = findViewById(R.id.gesturepwd_setting_preview_3);
	    this.mPreViews[1][1] = findViewById(R.id.gesturepwd_setting_preview_4);
	    this.mPreViews[1][2] = findViewById(R.id.gesturepwd_setting_preview_5);
	    this.mPreViews[2][0] = findViewById(R.id.gesturepwd_setting_preview_6);
	    this.mPreViews[2][1] = findViewById(R.id.gesturepwd_setting_preview_7);
	    this.mPreViews[2][2] = findViewById(R.id.gesturepwd_setting_preview_8);
	  }
	  
	  private void updatePreviewViews()
	  {
	    if (this.mChosenPattern == null) 
	    	return ; 
	    Iterator localIterator = this.mChosenPattern.iterator();
	    while (localIterator.hasNext())
	    {
	    	LockPatternView.Cell localCell = (LockPatternView.Cell)localIterator.next();
	        mPreViews[localCell.getRow()][localCell.getColumn()].setBackgroundResource(R.drawable.pattern_preview_focus);
	    }
	  }
	  
	  public void clickResetPattern()
	  {
	    this.mResetTextView.setVisibility(View.GONE);
	    this.mUiStage = Stage.Introduction;
	    this.mHeaderText.setTextColor(0xff000000);
	    this.mHeaderText.setText(R.string.lockpattern_create_tip);
	    for (int i = 0; i < 3; i++) {
	      for (int j = 0; j < 3; j++) {
	        this.mPreViews[i][j].setBackgroundResource(R.drawable.pattern_preview);
	      }
	    }
	  }
}
